package org.batatasframework.support.database.sql.where;

import java.util.ArrayList;
import java.util.List;

import org.batatasframework.support.database.LogicSymbol;
import org.batatasframework.support.database.sql.QueryParameter;


/**
 * 括号，用括号把指定的查询条件归在一起
 * @author jackson
 *
 */
public class QueryFragmentBrackets implements QueryFragment{
	
	private final LogicSymbol logic;
	
	private final List<QueryFragment> fragments = new ArrayList<>();
	
	public QueryFragmentBrackets(LogicSymbol logic){
		this.logic = logic;
	}
	
	public QueryFragmentBrackets(){
		this(LogicSymbol.AND);
	}
	
	public QueryFragmentBrackets append(QueryFragment fragment){
		this.fragments.add(fragment);
		return this;
	}

	public QueryFragmentBrackets append(QueryFragment... fragments){
		for(QueryFragment fragment : fragments){
			this.fragments.add(fragment);
		}
		return this;
	}

	@Override
	public void parse(LogicSymbol logic, StringBuilder sql, List<QueryParameter> paramenters) throws Exception {
		if(fragments.size() == 1){
			
			fragments.get(0).parse(logic, sql, paramenters);
			
		}else if(fragments.size() > 1){
			
			sql.append(logic.getValue()).append('(');
			LogicSymbol bodyLogic = LogicSymbol.NULL;
			
			for(QueryFragment fragment : fragments){
				fragment.parse(bodyLogic, sql, paramenters);
				
				bodyLogic = this.logic;
			}
			
			sql.append(')');
		}
	}
}
